import config
import stt
import tts
import commands
from fuzzywuzzy import fuzz
import datetime
import webbrowser
import random
import customtkinter as CTk
import hashlib
import json
from CTkMessagebox import CTkMessagebox
import os

class CheckWindow(CTk.CTkToplevel):
    def __init__(self):
        super().__init__()
        self.overrideredirect(True)
        self.font =("Helvetica", 24)

        self.title("Ввод парольной фразы")
        self.password_info = CTk.CTkLabel(self, text="Необходимо ввести пароль.", wraplength=350)
        self.password_info.configure(font=self.font)
        self.password_info.pack(pady=10)

        self.input_label1 = CTk.CTkLabel(self, text="Введите пароль:")
        self.input_label1.configure(font=self.font)
        self.input_label1.pack(pady=5)

        self.password_entry1 = CTk.CTkEntry(self, show="*", width=200, font=("Arial Unicode MS", 12))
        self.password_entry1.configure(font=self.font)
        self.password_entry1.pack(pady=5)

        self.save_button = CTk.CTkButton(self, text="Подтвердить", command=self.check_password)
        self.save_button.configure(font=self.font)
        self.save_button.pack(pady=10)

        self.exit_button = CTk.CTkButton(self, text="Отменить", command=self.on_close)
        self.exit_button.configure(font=self.font)
        self.exit_button.pack(pady=10)

        self.voice_button = CTk.CTkButton(self, text="Голосовой ввод")
        self.voice_button.configure(font=self.font)
        self.voice_button.pack(pady=10)
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        window_width = self.winfo_width()
        window_height = self.winfo_height()

        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))

        self.geometry(f"+{x}+{y}")
        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.grab_set()

        self.focus_set()
        self.wait_window()

    def check_password(self):
        password1 = self.password_entry1.get().lower()
        if self.check_password_f(password1):
            CTkMessagebox(title="Успех",
                          message="Пароль верный!",
                          icon="check",
                          option_1="OK")
            self.on_close()
        else:
            CTkMessagebox(title="Ошибка",
                          message="Пароли не совпадают!",
                          icon="cancel",
                          option_1="Попробовать еще раз")

    def on_close(self):
        self.grab_release()
        self.destroy()

    def generate_salt(self):
        salt = os.urandom(16)
        with open("test.json", "w", encoding="cp1251") as f:
            json.dump({"trest": salt.hex()}, f, ensure_ascii=False)
        with open("settings.json", "r", encoding="cp1251") as f:
            sett = json.load(f)

        with open("test.json", "r", encoding="utf-8") as f:
            salt2 = bytes.fromhex(json.load(f)["trest"])
            hashed_password = self.hash_password(sett["password"], salt2)
            sett["password"] = hashed_password
            with open("settings.json", "w", encoding="cp1251") as f:
                json.dump(sett, f)



    def hash_password(self, password, salt):
        salted_password = salt + password.encode('cp1251')
        hashed_password = hashlib.sha256(salted_password).hexdigest()
        print(hashed_password)
        return hashed_password

    def check_password_f(self, password):

        with open("test.json", "r", encoding="utf-8") as f:
            salt = bytes.fromhex(json.load(f)["trest"])
        with open("settings.json", "r", encoding="cp1251") as f:
            sett = json.load(f)

            print(sett["password"])
        return sett["password"] == self.hash_password(password, salt)




def va_respond(voice: str, main_window):

    print(voice)
    if voice.startswith(config.VA_NAME):
        cmd = recognize_cmd(filter_cmd(voice))
        print(cmd)

        user_message = voice[len(config.VA_NAME):].strip()
        main_window._insert_message(user_message.capitalize(), "Вы")
        main_window.update()
        if cmd['cmd'] not in config.VA_CMD_LIST.keys():
            tts.va_speak("Извините, не могу вам ответить...", main_window)
            main_window._insert_message("Извините, не могу вам ответить...", "Ассистент")
            main_window.update()
        else:
            execute_cmd(cmd['cmd'], main_window)


def filter_cmd(raw_voice: str):
    cmd = raw_voice

    for x in config.VA_NAME:
        cmd = cmd.replace(x, "").strip()

    for x in config.VA_TBR:
        cmd = cmd.replace(x, "").strip()

    return cmd


def recognize_cmd(cmd: str):
    rc = {'cmd': '', 'percent': 60}
    for c, v in config.VA_CMD_LIST.items():
        for x in v:
            vrt = fuzz.ratio(cmd, x)
            if vrt > rc['percent']:
                rc['cmd'] = c
                rc['percent'] = vrt
    return rc


def execute_cmd(cmd: str,main_window):
    if cmd == 'help':
        commands.help(main_window)
    elif cmd == 'ctime':
        commands.dtme(main_window)
    elif cmd == 'joke':
        commands.jokes(main_window)
    elif cmd == 'mute_on' or cmd == 'mute_off':
        commands.mute()
    elif cmd == 'screen':
        commands.screen(main_window)
    elif cmd == 'open_browser':
        webbrowser.open("https://ya.ru/")
    elif cmd == 'open_yt':
        webbrowser.open("https://www.youtube.com")

    elif cmd == 'open_music':
        webbrowser.open("https://music.yandex.ru/home")
        time.sleep(6)
        commands.music_on(main_window)
    elif cmd == 'music_off':
        commands.music_off(main_window)
    elif cmd == 'music_save':
        commands.music_like(main_window)
    elif cmd == 'music_next':
        commands.music_next()
    elif cmd == 'music_prev':
        commands.music_prev()
    elif cmd == 'open_system':
        commands.system_E(main_window)

    elif cmd == 'create_file':
        commands.create_file(main_window)

        commands.edit_doc(main_window)

    elif cmd == 'create_mail':
        check=CheckWindow()

        webbrowser.open("https://mail.yandex.ru")
        commands.create_emai(main_window)

    elif cmd == 'support':
        sp = ['Я знаю, что сейчас тебе тяжело, но ты справишься. Ты можешь преодолеть все трудности.', 'ы заслуживаешь всего самого лучшего. Не забывай об этом!']
        tts.va_speak(random.choice(sp), main_window)
    elif cmd == 'thanks':
        thx = ['Благодарю', 'Так мило с вашей стороны', 'Большое спасибо',
               'Очень признательна', 'Правда? Теперь можно и не стараться', 'Вы такой искренний человек.']
        tts.va_speak(random.choice(thx), main_window)
    elif cmd == 'turn_off':
        bye = ['До свидания', 'До скорой встречи', 'Берегите себя',
               'С нетерпением буду ожидать нашей следующей встречи']
        tts.va_speak(random.choice(bye), main_window)
        exit()




